#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-09-19 14:05:15
# @Author  : Your Name (you@example.org)
# @Link    : link
# @Version : 1.0.0

import json

from flask import Flask, request,jsonify
from flask_cors import *

from dbutils import dbhandler
from tables import Authority, BaseData

app = Flask(__name__)
CORS(app, supports_credentials=True)


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/base')
def base_data():
    tempdict = {}
    datalist = []
    b = BaseData.BaseData()
    _dict = dbhandler.get_base_data()
    for _list in _dict['data']:
        datalist.append(b.get_value(_list))
    tempdict['list'] = datalist
    jsond = json.dumps(tempdict)
    return jsond


@app.route("/update", methods=['POST'])
def update_data():
    if request.method == 'POST':
        _str = request.form['record']
        _uid = request.form['uid']
        _dict = json.loads(_str)
        # keys = _dict.keys()
        # values = [_dict[val] for val in keys]
        req = dbhandler.update_base_data(_dict)
        return json.dumps(req)


@app.route("/delete", methods=["POST"])
def delete_data():
    if request.method == 'POST':
        id_list = request.form['id_list']
        _uids = id_list[:-1].split(',')
        req = dbhandler.delete_base_data(_uids)
        return json.dumps(req)


@app.route("/upload_single", methods=["POST"])
def upload_single():
    if request.method == 'POST':
        _str = request.form['record']
        _dict = json.loads(_str)
        req = dbhandler.insert_base_data_single(_dict)
        return json.dumps(req)


@app.route("/upload_batch", methods=["POST"])
def upload_batch():
    if request.method == 'POST':
        _str = request.form['data']
        _dict_list = json.loads(_str)
        # 15/11/9 三种类型的情况，还有其他的情况，后面再做处理
        # _dict 进来以后就自动排序了
        dbhandler.insert_base_data_batch(_dict_list)
        return 'text'
    pass


@app.route("/load_json",methods=["GET","POST"])
def get_geojson():
    import os
    #print os.getcwd()
    str_ = ''
    _json = r"F:\hubu\gist2\server\test\wuhan.json"
    with open(_json, 'r') as r:
        lines = r.readlines()
        for line in lines:
            line = line.replace("\n","")
            str_ = str_ + line
    return str_


@app.route("/login", methods=["POST", "GET"])
def login_handle():
    if request.method == "GET":
        args = request.args
        _str_username = args['name']
        _str_password = args['psd']
        verify_pass = dbhandler.verify_user([_str_username, _str_password])
        return json.dumps(verify_pass)


if __name__ == '__main__':
    import modules
    app.run()
    # app.run(port='0.0.0.0', port=8888)

